import { KWError } from "./common/error";
import { Configuration, App, Config } from '@midwayjs/decorator';
import { Application } from '@midwayjs/koa';
import * as bodyParser from 'koa-bodyparser';
import * as session from 'koa-session';
import * as cors from 'koa2-cors';
import * as typegoose from '@midwayjs/typegoose';
import { SESSION_MAX_AGE } from "./constants";
import { KWCode } from "./common/code";
import SessionMongoStore from "./util/session-store";
import { IMidwayContainer } from "@midwayjs/core";
import logger from "./middleware/logger.middleware";
import { serverMoment } from "./util/utilities";
import KWContext from "./common/context";

@Configuration({
  conflictCheck: true,
  imports: [typegoose],
  importConfigs: ['./config/']
})
export class ContainerLifeCycle {
  @App()
  app: Application;

  @Config()
  session: Partial<session.opts>;

  // 项目配置加载完后可执行脚本
  async onConfigLoad(container: IMidwayContainer) {
    // const initialization = await container.getAsync<Initialization>('initialization');
    // initialization.exec();
  }

  async onReady() {
    this.app.use(logger());
    this.app.use(bodyParser());
    this.app.use(
      cors({
        origin: '*',
        allowMethods: ['GET', 'POST', 'PUT', 'DELETE']
      })
    );
    this.app.use(
      session(
        {
          key: 'FEEDBACK_V2_SESSION',
          maxAge: SESSION_MAX_AGE,
          rolling: true,
          signed: false,
          store: new SessionMongoStore()
        },
        this.app
      )
    );
    this.app.use(async (ctx: KWContext, next: any) => {
      try {
        await next();
      } catch (error) {
        if (error.toHttpResponseValue) {
          const fbError = <KWError>error;
          ctx.response.body = fbError.toHttpResponseValue(ctx.oid);
        } else {
          ctx.response.body = {
            st: serverMoment().unix(),
            oid: ctx.oid,
            code: KWCode.internalError,
            message: error.message || `server error ${ctx.originalUrl}`
          };
        }
      }
    });
  }
}
